//
//  MNDGestureViewController.m
//  miniwangdai2
//
//  Created by 谭谭伟 on 17/3/13.
//  Copyright © 2017年 谭谭伟. All rights reserved.
//

#import "MNDGestureViewController.h"

#import "GestureView.h"
#import "UserDefaultsTool.h"
#import <Masonry.h>
#import "CALayer+Shake.h"
#import <SVProgressHUD.h>
//提示label底部与手势图间距
#define LabBottomMargin 60
//手势图偏离centerY间距
#define GestureViewCenterY 100
//顶部手势图与提示label间距
#define TopGestureViewMargin 20
//顶部宽高
#define TopViewWH 60

//默认间距
#define Margin 20

//手势按钮宽高
#define BtnSizeWH [UIScreen mainScreen].bounds.size.width/7
//#define FinishGestureSet @"finishGestureSet"

@interface MNDGestureViewController ()<GestureViewDelegate>




/* 手势view */
@property (strong, nonatomic) GestureView *gestureView;

/* 底部重新绘制按钮 */
@property (strong, nonatomic) UIButton *resetButton;
/* <#Annotation#> */
//@property (assign, nonatomic) BOOL secondSet;
/* 密码状态 */
@property (strong, nonatomic) NSString *setGesture;
/* 修改密码状态记录 */
@property (assign, nonatomic)BOOL changeGesture;

@end

@implementation MNDGestureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    // Do any additional setup after loading the view, typically from a nib.
    
  
    //查看是设置密码还是核对密码
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docuPath stringByAppendingPathComponent:@"setGesture"];
    _setGesture = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    if ([_setGesture isEqualToString:@"NO"]) {
        
        UILabel *navLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 62, 20)];
        navLabel.text = @"修改手势密码";
        navLabel.textColor = [UIColor whiteColor];
        
       self.navigationItem.titleView = navLabel;
    }else if(([UserDefaultsTool boolForKey:@"closeGesture"] == YES)){
        UILabel *navLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 62, 20)];
        navLabel.text = @"关闭手势密码";
        //            navLabel.font = [UIFont systemFontOfSize:<#(CGFloat)#>]
        navLabel.textColor = [UIColor whiteColor];
        self.navigationItem.titleView = navLabel;
    
    }
    else {
        UILabel *navLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 62, 20)];
        navLabel.text = @"手势密码";
        //            navLabel.font = [UIFont systemFontOfSize:<#(CGFloat)#>]
        navLabel.textColor = [UIColor whiteColor];
        self.navigationItem.titleView = navLabel;
    }
    
    [self setupUI];
    
    if (![_setGesture isEqualToString:@"NO"]) {
        //如果还没有设置手势密码,发送通知让网页显示未设置
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WithoutSetGesture" object:nil];
        
    } else {
 
    }


 
}


- (void)viewWillAppear:(BOOL)animated {
    
    if([UserDefaultsTool boolForKey:@"confirmPassword"] == YES) {
        //隐藏nav
        super.navigationController.navigationBarHidden = YES;
    }else {
        //显示nav
        super.navigationController.navigationBarHidden = NO;
    }

}
#pragma mark -搭建界面

- (void)setupUI {
    
     // -------- 设置手势图 --------
    GestureView *gestureView = [[GestureView alloc]initWithFrame:self.view.bounds];
    gestureView.delegate = self;
    //记录
    _gestureView = gestureView;
    //提示label
    _tipLabel = [[UILabel alloc]init];
    _tipLabel.font = [UIFont systemFontOfSize:14];
    if (![_setGesture isEqualToString:@"NO"]) {
         _tipLabel.text = @"为了您账户的安全,请绘制解锁图案";
    }else {
        _tipLabel.text = @"请输入原手势密码";
    
    }
   
    
    // -------- 顶部显示手势图 --------
    _topGestureView = [[TopGestureView alloc]initWithFrame:self.view.bounds];
    
    // -------- 重新绘制按钮 --------
    _resetButton = [[UIButton alloc]init];
    [_resetButton setTitle:@"重新绘制" forState:UIControlStateNormal];
    [_resetButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    //添加点击事件
    [_resetButton addTarget:self action:@selector(clickResetButton:) forControlEvents:UIControlEventTouchUpInside];
    
    //先让其隐藏
    _resetButton.hidden = YES;
    
    // -------- 忘记手势密码按钮 --------
    _forgetPasswordBtn = [[UIButton alloc] init];
    [_forgetPasswordBtn setTitle:@"忘记手势密码" forState:UIControlStateNormal];
     _forgetPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_forgetPasswordBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _forgetPasswordBtn.hidden = YES;
    //添加点击事件
    [_forgetPasswordBtn addTarget:self action:@selector(clickForgetPasswordBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    // -------- 换号登录按钮 --------
    _otherAcountLoginBtn = [[UIButton alloc] init];
    [_otherAcountLoginBtn setTitle:@"其他账号登录" forState:UIControlStateNormal];
    _otherAcountLoginBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_otherAcountLoginBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    _otherAcountLoginBtn.hidden = YES;
    //添加点击事件
    [_otherAcountLoginBtn addTarget:self action:@selector(clickOtherAcountLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    // -------- 添加 --------
    [self.view addSubview:gestureView];
    [self.view addSubview:_tipLabel];
    [self.view addSubview:_topGestureView];
    [self.view addSubview:_resetButton];
    [self.view addSubview:_forgetPasswordBtn];
    [self.view addSubview:_otherAcountLoginBtn];
//
    
    // -------- 布局 --------
    [gestureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view).mas_offset(GestureViewCenterY);
        make.width.height.mas_equalTo(self.view.bounds.size.width);
    }];
    
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(gestureView.mas_top).mas_offset(-LabBottomMargin*0.5);
    }];
    
    [_topGestureView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(_tipLabel.mas_top).mas_offset(-TopGestureViewMargin);
        make.width.height.mas_equalTo(TopViewWH);
    }];
    
    [_resetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(gestureView.mas_bottom).mas_offset(-LabBottomMargin);
    }];
    
    [_forgetPasswordBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).mas_offset(BtnSizeWH);
        make.top.equalTo(self.gestureView.mas_bottom).mas_offset(-Margin);
        make.height.mas_equalTo(80);
    }];

    [_otherAcountLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).mas_offset(-BtnSizeWH);
        make.top.equalTo(self.gestureView.mas_bottom).mas_offset(-Margin);
        make.height.mas_equalTo(80);
    }];
    
    

}


//重新绘制事件
- (void)clickResetButton:(UIButton *)button {
    _resetButton.hidden = YES;
    _gestureView.password = nil;
    [_gestureView savePassword:nil];
    _tipLabel.text = @"为了您账户的安全,请绘制解锁图案";
    _tipLabel.textColor = [UIColor blackColor];
    
    //顶部按钮归位
    for (UIButton *button in _topGestureView.selectBtnArr) {
        button.selected = NO;
    }
}

//第二次输入设置密码
- (void)secondSetPassword {
    //    [self comparePassword];
    
}

#pragma mark -GestureViewDelegate
//设置密码
- (void)gestureLockSetPassword:(NSString *)password gestureView:(GestureView *)gestureView {


    
    if (![_setGesture isEqualToString:@"NO"] && (_changeGesture != YES)) {//如果还没有设置手势

        if(gestureView.selectBtnArr.count < 4) {
            _tipLabel.text = @"请设置至少4位手势密码";
            _tipLabel.textColor = [UIColor redColor];
            [_tipLabel.layer shake];
            return;
        } else {//二次确定设置的密码
            _tipLabel.text = @"请再次输入密码";
            _tipLabel.textColor = [UIColor blackColor];
            _resetButton.hidden = NO;
//            _secondSet = YES;
            [gestureView savePassword:password];
            
//            //取到保存的密码
//            NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//            NSString *passwordFilePath = [docuPath stringByAppendingPathComponent:@"password"];
//            NSString *savePassword= [NSKeyedUnarchiver unarchiveObjectWithFile:passwordFilePath];
            for (int i = 0; i < password.length; i++) {
                NSString *select = [password substringWithRange:NSMakeRange(i, 1)];
                UIButton *selectBtn = [_topGestureView viewWithTag:select.intValue];
                selectBtn.selected = YES;
                
                //记录保存
                [_topGestureView.selectBtnArr  addObject:selectBtn];
            }
            
        }
    }else {//修改密码
        //重置密码为空
        _tipLabel.text = @"请输入新密码";
        _tipLabel.textColor = [UIColor blackColor];
        _changeGesture = NO;
        _setGesture = @"YES";
        

    }
    }

//密码正确
- (void)gestureLockPasswordRight:(GestureView *)gestureView {
    
    //是否验证密码
    BOOL confirmPassword = [UserDefaultsTool boolForKey:@"confirmPassword"];
    
    //判断是否设置密码
    if ((![_setGesture isEqualToString:@"NO"])&& (_changeGesture != YES)) {//设置密码
        [SVProgressHUD showSuccessWithStatus:@"设置成功"];
        
        //记录登陆状态
        [UserDefaultsTool saveBool:YES forKey:@"signIn"];
        
        [gestureView savePassword:gestureView.password];
        //发送通知告诉网页手势已设置
        [[NSNotificationCenter defaultCenter] postNotificationName:@"FinishSetGesture" object:nil];
        //保存设置状态
        NSString *setGesture = @"NO";
        NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [docuPath stringByAppendingPathComponent:@"setGesture"];
        [NSKeyedArchiver archiveRootObject:setGesture toFile:filePath];
       [self.navigationController popViewControllerAnimated:YES];
        
        
    }else if (confirmPassword == YES) {
        [SVProgressHUD showSuccessWithStatus:@"密码正确"];
        [UserDefaultsTool saveBool:NO forKey:@"confirmPassword"];
        [self.navigationController popViewControllerAnimated:YES];
        
        
    }else {
        _changeGesture = YES;
        _setGesture = nil;
        [gestureView savePassword:nil];
        [self gestureLockSetPassword:gestureView.password gestureView:gestureView];
        
    }
    
    
    //重置错误的次数
    NSString *erroCount = @"5";
    [UserDefaultsTool saveObject:erroCount forKey:@"erroCount"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [SVProgressHUD dismiss];
        
    });
    
}

//密码错误
- (void)gestureLockPasswordError:(GestureView *)gestureView {
    //是否验证密码
    BOOL confirmPassword = [UserDefaultsTool boolForKey:@"confirmPassword"];
    //取出还可以错误的次数
    NSString *erroCount = [UserDefaultsTool objetForKey:@"erroCount"];
    NSInteger erroCountInt = erroCount.integerValue;
    if (_setGesture==nil || _changeGesture == NO ) {
        _tipLabel.text = @"密码不一致";
        _tipLabel.textColor = [UIColor redColor];
    } else {
        _tipLabel.text = @"密码错误";
        _tipLabel.textColor = [UIColor redColor];
        
    }
    if (confirmPassword == YES) {
        erroCountInt--;
        _tipLabel.text = [NSString stringWithFormat:@"手势密码错误,还可以输入%zd次",erroCountInt];
        _tipLabel.textColor = [UIColor redColor];
        
        [UserDefaultsTool saveObject:[NSString stringWithFormat:@"%zd",erroCountInt] forKey:@"erroCount"];
        if (erroCountInt == 0) {
           
            //登出
            [self signOn];
//            //重制密码错误次数并登出
//            erroCountInt = 5;
//            [UserDefaultsTool saveObject:[NSString stringWithFormat:@"%zd",erroCountInt] forKey:@"erroCount"];
            
            
        }
    }
    
    [_tipLabel.layer shake];
}

#pragma mark - 设置topGestureView的状态
- (void)setTopGestureViewStatus {
    //取到保存的密码
    NSString *docuPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *passwordFilePath = [docuPath stringByAppendingPathComponent:@"password"];
    NSString *password= [NSKeyedUnarchiver unarchiveObjectWithFile:passwordFilePath];
    for (int i = 0; i < password.length; i++) {
        NSString *select = [password substringWithRange:NSMakeRange(i, 1)];
        UIButton *selectBtn = [_topGestureView viewWithTag:select.intValue];
        selectBtn.selected = YES;
        
    }

}


#pragma mark -点击事件
//忘记手势密码点击事件
- (void)clickForgetPasswordBtn:(UIButton *)button {
    
    //提示label
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"忘记手势密码，需要重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *setNetworkAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }];
    //取消设置
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self signOn];
    }];
    
    //添加到控制器
    [alertController addAction:setNetworkAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];

}



//其他账号登录
- (void)clickOtherAcountLoginBtn:(UIButton *)button {
    //提示label
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"使用其他账号，需要重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *setNetworkAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }];
    //取消设置
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self signOn];
    }];
    
    //添加到控制器
    [alertController addAction:setNetworkAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];

}


//登出
- (void)signOn {

    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"signOut" object:nil];
//    [self.navigationController popViewControllerAnimated:NO];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
